package basiclocaloperator.beanoperate;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.junit.Test;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BeanOperate {

    public static void main(String[] args) throws Exception {
        Person person = new Person();
        person.setAge(20);
        person.setName("大明");
        person.setPassword("jializhen");
        person.setBirthday(new Date());
        test5(person);
    }


    public static <T> void test5(T t) throws Exception {
        BeanInfo info = Introspector.getBeanInfo(t.getClass(), Object.class);
        PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : descriptors) {
            System.out.println(descriptor.getName() + ":" + descriptor.getReadMethod().invoke(t, null));
        }
    }


    @Test
    public void test1() throws Exception {
        BeanInfo info = Introspector.getBeanInfo(Person.class, Object.class);
        PropertyDescriptor[] pds = info.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            System.out.println(pd.getName());
        }
    }

    @Test
    public void test2() throws Exception {
        Person p = new Person();
        PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);
        Method method = pd.getWriteMethod();
        method.invoke(p, 45);
        System.out.println(pd.getReadMethod().invoke(p, null));

    }

    @Test
    public void test3() throws Exception {
        Person person = new Person();

        ConvertUtils.register(new Converter() {

            @Override
            public Object convert(Class type, Object value) {
                // TODO Auto-generated method stub
                String string = (String) value;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                try {
                    return sdf.parse(string);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return new Date(System.currentTimeMillis());
                }
            }
        }, Date.class);

        BeanUtils.setProperty(person, "age", 36);
        BeanUtils.setProperty(person, "birthday", "1988-03-09");
        System.out.println(person.getAge());
        System.out.println(person.getBirthday());
    }
}
